<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="出库物品" prop="itemName">
        <el-input v-model="queryParams.itemName" placeholder="请输入物品名称" clearable></el-input>
      </el-form-item>

      <el-form-item label="出库状态" prop="isReturn">
        <el-select v-model="queryParams.isReturn" placeholder="请选择出库状态" clearable>
          <el-option
            v-for="dict in dict.type.is_return"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="归还情况" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择归还情况" clearable>
          <el-option
            v-for="dict in dict.type.status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">

      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['warehousemanager:outwarehouse:remove']"
        >删除</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['warehousemanager:outwarehouse:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="outwarehouseList" @selection-change="handleSelectionChange" @sort-change="handleSortChange">
      <el-table-column type="selection"  width="55" align="center" />
      <el-table-column label="序号" align="center" width="55" type="index" :index.sync="indexMethod" />
      <el-table-column label="物品名称" align="center" prop="item.itemName" />
      <el-table-column label="出库仓库" align="center" prop="dept.deptName" />
      <el-table-column label="出库数量" align="center" prop="itemNum" />
      <el-table-column label="待归还数量" align="center" prop="returnNum" />
      <el-table-column label="出库状态" align="center" prop="isReturn">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.is_return" :value="scope.row.isReturn"/>
        </template>
      </el-table-column>
      <el-table-column label="出库时间" align="center" prop="outTime" width="180" :sort-orders="['descending','ascending']" sortable="custom">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.outTime, '{y}-{m}-{d} {h}:{m}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="归还时间" align="center" prop="returnTime" width="180" :sort-orders="['descending','ascending']" sortable="custom">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.returnTime, '{y}-{m}-{d} {h}:{m}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="归还情况" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            :disabled="scope.row.status==2?true:false || scope.row.status==3?true:false"
            v-hasPermi="['warehousemanager:outwarehouse:edit']"
          >归还登记</el-button>
        </template>
      </el-table-column>

    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 归还登记操作对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <div style="display:flex;text-align:center;justify-content:center">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="物品名称" prop="itemName">
          <el-input style="display:flex;" v-model="form.itemName" placeholder="请输入出库物品名称" :disabled="true">

          </el-input>
        </el-form-item>


        <el-form-item label="物品数量" prop="itemNumInput">
          <el-input v-model="form.itemNumInput" placeholder="请输入归还物品数量" clearable/>
        </el-form-item>

        <el-form-item label="归还时间" prop="returnTime">
          <el-date-picker clearable
            v-model="form.returnTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择归还时间">
          </el-date-picker>
          </el-form-item>

      </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOutwarehouse, getOutwarehouse, delOutwarehouse, addOutwarehouse, updateOutwarehouse, } from "@/api/warehousemanager/outwarehouse";
import {getItem,updateItem} from "@/api/warehousemanager/item";

export default {
  name: "Outwarehouse",
  dicts: ['is_return', 'status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 出库管理表格数据
      outwarehouseList: [],
      // 弹出层标题
      title: "",
      //表内禁用物品名
      disabled:false,
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        itemId: null,
        toWarehouseId:this.$store.getters.deptId,
        itemNum: null,
        returnNum:null,
        isReturn: null,
        outTime: null,
        returnTime: null,
        status: null,
        itemName: null,
      },
      // 表单参数
      form: {
        itemName:null,
        itemNum: null,
        returnNum:null,
        returnTime: null,
        status: null,
        itemNumInput: null,
      },

      // 表单校验
      rules: {
        itemNumInput: [
          { required: true,message: "归还数量不能为空", trigger: "blur" },
          {pattern:/^[1-9]\d*$/,message:'请输入正确数字值'},
          { required: true,  trigger: "blur" }
        ],
        returnTime:{required: true,message:"归还时间不能为空"},
      },
    };
  },

  created() {
    this.getList();
  },
  methods: {
    //自增序号
    indexMethod(index) {
      return (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1;
    },
    /** 查询出库管理列表 */
    getList() {
      this.loading = true;
      listOutwarehouse(this.queryParams).then(response => {
        this.outwarehouseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.outId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },

    /** 排序 */
    handleSortChange(column){
      this.queryParams.orderByColumn=column.prop;
      this.queryParams.isAsc=column.order;
      this.getList();
    },
    /** 归还登记按钮操作 */
    handleUpdate(row) {
      this.reset();
      const outId = row.outId || this.ids;
      getOutwarehouse(outId).then(response => {
        const formData = { ...response.data };
        formData.itemNumInput = formData.returnNum;
        this.form = formData;
        this.open = true;
        this.title = "归还登记";
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const outIds = row.outId || this.ids;
      this.$modal.confirm('是否确认删除？').then(function() {
        return delOutwarehouse(outIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const newReturnNum = this.form.returnNum - this.form.itemNumInput;
          if (newReturnNum >= 0) {
            this.form.returnNum = newReturnNum;
            if (this.form.returnNum === 0) {
              this.form.status = 2;
            } else if (this.form.returnNum > 0) {
              this.form.status = 1;
            }
            updateOutwarehouse(this.form).then(response => {
              getItem(this.form.itemId).then(res=>{
                let formUpdate = {
                  itemId: this.form.itemId,
                  itemName: this.form.itemName,
                  itemNum: Number(res.data.itemNum) + Number(this.form.itemNumInput),
                };
                  updateItem(formUpdate).then(()=>{
                    this.$modal.msgSuccess("归还成功");
                    this.open = false;
                    this.getList();
                  })
              })

            })
          } else {
            this.$message.error("归还物品数量不能超过出库物品数量");
          }
        }
      });
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('warehousemanager/outwarehouse/export', {
        ...this.queryParams
      }, `outwarehouse_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
